package com.kpx.app.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.bumptech.glide.Glide;
import com.kpx.app.Application;
import com.kpx.app.R;
import com.kpx.app.activity.ActivityMyPhotosNew;
import com.kpx.app.bean.BannerBean;
import com.kpx.app.utils.systemutils.SystemUtil;
import com.kpx.app.utils.uiutils.DisplayUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.MyWebView;
import com.kpx.app.view.webview.MyShopWebChromeClient;
import com.kpx.app.view.webview.MyWebViewClient;
import com.kpx.app.view.webview.ScriptInterface;
import com.kpx.app.utils.datautils.FileUtils;
import com.kpx.app.view.TitleView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoaderInterface;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.PhotoPreviewActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * User: 陈聪(617909447@qq.com)
 * Date: 2016-07-05
 * Time: 08:57
 * FIXME
 */
public class UIUtils {
    /**
     * 初始化上下拉刷新
     */
    public static void initRefreshView(XRefreshView outView) {
        outView.setPullLoadEnable(true);
        outView.setPinnedTime(1000);
        outView.setAutoLoadMore(true);
//		outView.setCustomHeaderView(new CustomHeader(this));
//		outView.setCustomHeaderView(new XRefreshViewHeader(this));
        outView.setMoveForHorizontal(true);
//        outView.setCustomFooterView(new CustomerFooter(this));
//		outView.setPinnedContent(true);
    }

    public static void setColorText(Context context, TextView txt, String str, int color, String allStr) {
        SpannableString s = new SpannableString(allStr+str);
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(context.getResources().getColor(color)), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        txt.setText(s);
    }
    public static void setColorText2(Context context, TextView txt, String str, int color, String allStr) {
        SpannableString s = new SpannableString(allStr);
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(context.getResources().getColor(color)), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        txt.setText(s);
    }
    public static void setColorText3(Context context, TextView txt, ArrayList<String>  strs, int color, String allStr) {
        SpannableString s = new SpannableString(allStr);
        for (int i = 0; i < strs.size(); i++) {
            // 将名字转换为蓝色
            Pattern p = Pattern.compile(strs.get(i));
            Matcher m = p.matcher(s);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new ForegroundColorSpan(context.getResources().getColor(color)), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        txt.setText(s);

    }

    /**
     * 初始化标题栏(基本初始化，其他属性需自己配置)
     */
    public static TitleView setComTitle(Context context, String title) {
        TitleView title_view = (TitleView) ((Activity) context).findViewById(R.id.titleview);
        setTitle(title_view, title);
        return title_view;
    }

    /**
     * 初始化标题栏(基本初始化，其他属性需自己配置)
     */
    public static TitleView setTitle(TitleView title_view, String title) {
        title_view.setFitsSystemWindows(true);
        title_view.setTitle(title);
        title_view.setBackFinish();
        title_view.setTitleColor(Application.instance.getResources().getColor(R.color.black_0a));
        title_view.setTitleBgColor(Application.instance.getResources().getColor(R.color.white));
        title_view.setTitleVisibility(View.VISIBLE);
//        title_view.setTitleHeight(150);//设置高度
        return title_view;
    }

    /**
     * 初始化标题栏(基本初始化，其他属性需自己配置)
     */
    public static TitleView setNormalTitle(TitleView title_view, String title) {
        title_view.setFitsSystemWindows(true);
        title_view.setTitle(title);
        title_view.setBackFinish();
        title_view.setTitleVisibility(View.VISIBLE);
//        title_view.setTitleHeight(150);//设置高度
        return title_view;
    }

    /**
     * 初始化标题栏(基本初始化，其他属性需自己配置)
     */
    public static TitleView setTitle(Context context, int color_bg, int color_txt_title, String title) {
        TitleView title_view = (TitleView) ((Activity) context).findViewById(R.id.titleview);
        title_view.setFitsSystemWindows(true);
        title_view.setTitle(title);
        title_view.setBackFinish();
        title_view.setTitleColor(context.getResources().getColor(color_txt_title));
        title_view.setTitleBgColor(context.getResources().getColor(color_bg));
        title_view.setTitleVisibility(View.VISIBLE);
//        title_view.setTitleHeight(150);//设置高度
        return title_view;
    }

    /**
     * 弹出没有设置支付密码Dialog
     */
    public static void popupAlertNoPayPwdDialog(final Context context) {
        View dialogView = LayoutInflater.from(context).inflate(R.layout.fragment_no_pay_pwd_dialog, null, false);
        final AlertDialog mNoPayPwdDialog = new android.support.v7.app.AlertDialog.Builder(context).setView(dialogView).create();
        mNoPayPwdDialog.getWindow().setWindowAnimations(R.style.DialogFadeAnimation);
        mNoPayPwdDialog.getWindow().setBackgroundDrawableResource(R.drawable.btn_radius_rectangle_white_normal);
        double temp = DisplayUtil.getScreenWidth(context) * 0.9;
        int temp1 = (int) temp;
        mNoPayPwdDialog.getWindow().setLayout(temp1, WindowManager.LayoutParams.WRAP_CONTENT);
        TextView noPayPwdBottomTextView = (TextView) dialogView.findViewById(R.id.noPayPwdBottomTextView);
        noPayPwdBottomTextView.setText(Html.fromHtml(getNoPayPwdText()));
        noPayPwdBottomTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(context, ActivityPayPassword.class);
//                context.startActivity(intent);
//                mNoPayPwdDialog.dismiss();
            }
        });
        mNoPayPwdDialog.show();
    }

    /**
     * 获取没有绑定银行卡下部文字
     *
     * @return
     */
    private static String getNoPayPwdText() {
        return "&nbsp;您尚未设定支付密码，如需进行<br/>＂付款＂与＂提现＂操作，请前往＂钱包＂<br/>&nbsp;<font color='#ff2d4b'>支付密码管理</font>进行设定！<font color='#ff2d4b'>现在去！</font>";
    }

    /**
     * 加载本地图片
     * http://bbs.3gstdy.com
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 设置通知栏背景颜色
     */
    public static void setNotifyColor(Context context, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(context, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(((Activity) context));
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(color);//通知栏所需颜色
        }
    }

    @TargetApi(19)
    public static void setTranslucentStatus(Context context, boolean on) {
        Window win = ((Activity) context).getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }


    /**
     * 初始化webview
     *
     * @version 1.0
     * @createTime 2015年11月1日, 下午3:48:17
     * @updateTime 2015年11月1日, 下午3:48:17
     * @createAuthor chencong
     * @updateAuthor
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    @SuppressLint({"JavascriptInterface", "NewApi"})
    @SuppressWarnings("deprecation")
    public static void initWebView(final Context context, MyWebView webView, View loadFailView) {
        initWebView(context, webView);
        MyWebViewClient m = new MyWebViewClient(context, webView);
        m.setLoadFailView(loadFailView);
        webView.setWebViewClient(m);
    }

    /**
     * 初始化webview
     *
     * @version 1.0
     * @createTime 2015年11月1日, 下午3:48:17
     * @updateTime 2015年11月1日, 下午3:48:17
     * @createAuthor chencong
     * @updateAuthor
     * @updateInfo (此处输入修改内容, 若无修改可不写.)
     */
    @SuppressLint({"JavascriptInterface", "NewApi"})
    @SuppressWarnings("deprecation")
    public static void initWebView(final Context context, MyWebView webView) {
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (url != null && url.startsWith("http://"))
                    ((Activity) context).startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            }
        });

        webView.setWebViewClient(new MyWebViewClient(context, webView));
        webView.setWebChromeClient(new MyShopWebChromeClient(context, webView));
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        // 设置webview的属性
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);// 支持js注入
        // 添加js交互接口类，并起别名 imagelistner
        webView.addJavascriptInterface(new ScriptInterface(context, webView), "android");
        settings.setLoadsImagesAutomatically(true);
        settings.setDefaultTextEncodingName("utf-8");// 已utf-8格式解析
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 适应屏幕，内容将自动换行
        settings.setUseWideViewPort(true);// 设置支持双击放大和缩小 设置适应屏幕
        settings.setLoadWithOverviewMode(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setDisplayZoomControls(false);
        settings.setSupportZoom(false);
        if (SystemUtil.getConnectivityStatus(context) == NetworkInfo.State.CONNECTED) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//没网，则从本地获取，即离线加载
        }
        settings.setDomStorageEnabled(true);// 开启DOM storage API功能
        // 开启 database storage API 功能 
        settings.setDatabaseEnabled(true);
        String cacheDirPath = FileUtils.getRootPath() + "webCache/";
        // 设置数据库缓存路径 
        settings.setDatabasePath(cacheDirPath);
        // 设置  Application Caches 缓存目录
        settings.setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        settings.setAppCacheEnabled(true);
        settings.setBuiltInZoomControls(true);
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    /**
     * 身份证号替换，保留前6位和后1位
     * <p>
     * 如果身份证号为空 或者 null ,返回null ；否则，返回替换后的字符串；
     *
     * @param idCard 身份证号
     * @return
     */
    public static String idCardReplaceWithStar(String idCard) {
        int length = idCard.length();
        if (length >= 7) {
            return idCard.replaceAll("(?<=\\d{6})\\d(?=\\d{1})", "*");
        } else {
            return idCard;
        }
    }

    /**
     * 身份证号替换，保留前6位和后1位
     * <p>
     * 如果身份证号为空 或者 null ,返回null ；否则，返回替换后的字符串；
     *
     * @param idCard 身份证号
     * @return
     */
    public static String phoneReplaceWithStar(String idCard) {
        int length = idCard.length();
        if (length >= 7) {
            return idCard.replaceAll("(?<=\\d{3})\\d(?=\\d{4})", "*");
        } else {
            return idCard;
        }
    }

    /**
     * 正则匹配
     *
     * @param rgx 正则
     * @param res 内容
     * @return
     */
    public static boolean checkData(String rgx, String res) {
        Pattern p = Pattern.compile(rgx);
        Matcher m = p.matcher(res);
        return m.matches();
    }

    /**
     * 正则匹配身份证
     *
     * @param str 内容
     * @return
     */
    public static boolean checkPNO(String str) {
        return checkData("^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$", str);
    }

    /**
     * Activity切换Fragment
     *
     * @param beingOpenedFragment 即将打开的Fragment
     * @param container           放置Fragment的容器
     * @param addToBackStack      是否放入后退栈中  true 放入,false 不放入
     * @param fadeAnim            true使用渐入渐出动画, false使用右入左出动画
     */
    public static <T extends Fragment> T switchFragment(Activity activity, T beingOpenedFragment, int container, boolean addToBackStack, boolean fadeAnim) {
        if (activity.isFinishing()) return null;
        FragmentManager fragmentManager = ((AppCompatActivity) activity).getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (fadeAnim) {
            transaction.setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out, R.anim.abc_fade_in, R.anim.abc_fade_out);
        } else {
            transaction.setCustomAnimations(R.anim.open_right_in, R.anim.close_left_out, R.anim.open_left_in, R.anim.close_right_out);
        }
        if (addToBackStack) {
            transaction.addToBackStack(beingOpenedFragment.getClass().getSimpleName());
        }
        transaction.replace(container, beingOpenedFragment, beingOpenedFragment.getClass().getSimpleName());
        transaction.commitAllowingStateLoss();
        return beingOpenedFragment;
    }

    public static void goQQChat(String qqnum) {
        if (TextUtils.isEmpty(qqnum)) {
            Toast.makeText(Application.instance, "联系方式有误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkApkExist(Application.instance, "com.tencent.mobileqq")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + qqnum + "&version=1"));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Application.instance.startActivity(intent);
        } else {
            Toast.makeText(Application.instance, "本机未安装QQ应用", Toast.LENGTH_SHORT).show();
        }
    }

    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static void iniBanner(Context context, Banner banner) {
        //一步搞定，设置图片就行了
//        banner.setImages(images);
        /////------------------------------自定的----------------------////
        //显示圆形指示器和标题
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置标题列表
//        banner.setBannerTitles()
        //设置指示器居中
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        /**
         * 可以选择设置图片网址，或者资源文件，默认用Glide加载
         * 如果你想设置默认图片就在xml里设置default_image
         * banner.setImages(images);
         */
        banner.setImageLoader(new ImageLoaderInterface() {
            @Override
            public void displayImage(Context context, Object path, View imageView) {
                ((ImageView) imageView).setScaleType(ImageView.ScaleType.CENTER_CROP);
                /**
                 * 这里你可以根据框架灵活设置
                 */
                Glide.with(context)
                        .load(((BannerBean) path).getIcon())
                        .fitCenter()
                        .placeholder(R.drawable.default_head_img)
                        .crossFade()
                        .into((ImageView) imageView);
            }

            @Override
            public View createImageView(Context context) {
                return null;
            }
        });
    }

    public static void getPhotos(int maxCount, List<PhotoInfo> mPhotoList, GalleryFinal.OnHanlderResultCallback callback) {
        FunctionConfig.Builder functionConfigBuilder = new FunctionConfig.Builder();
        functionConfigBuilder.setMutiSelectMaxSize(maxCount);
        functionConfigBuilder.setSelected(mPhotoList);//添加过滤集合
        functionConfigBuilder.setMutiSelect(true);//配置是否多选
        functionConfigBuilder.setEnableEdit(true);//开启编辑功能
        functionConfigBuilder.setEnableCrop(true);//开启裁剪功能
        functionConfigBuilder.setEnableRotate(true);//开启选择功能
        functionConfigBuilder.setEnableCamera(true);//开启相机功能
//            functionConfigBuilder.setCropWidth(int width)//裁剪宽度
//            functionConfigBuilder.setCropHeight(int height)//裁剪高度
//            functionConfigBuilder. setCropSquare(boolean)//裁剪正方形
//            functionConfigBuilder.setSelected(List)//添加已选列表,只是在列表中默认呗选中不会过滤图片
//            functionConfigBuilder. setFilter(List list)//添加图片过滤，也就是不在GalleryFinal中显示
//            functionConfigBuilder.takePhotoFolter(File file)//配置拍照保存目录，不做配置的话默认是/sdcard/DCIM/GalleryFinal/
//            functionConfigBuilder.setRotateReplaceSource(boolean)//配置选择图片时是否替换原始图片，默认不替换
//            functionConfigBuilder.setCropReplaceSource(boolean)//配置裁剪图片时是否替换原始图片，默认不替换
//            functionConfigBuilder.setForceCrop(boolean)//启动强制裁剪功能,一进入编辑页面就开启图片裁剪，不需要用户手动点击裁剪，此功能只针对单选操作
//            functionConfigBuilder.setForceCropEdit(boolean)//在开启强制裁剪功能时是否可以对图片进行编辑（也就是是否显示旋转图标和拍照图标）
        functionConfigBuilder.setEnablePreview(true);//是否开启预览功能
        final FunctionConfig functionConfig = functionConfigBuilder.build();
        GalleryFinal.openGalleryMuti(Application.REQUEST_CODE_GALLERY, functionConfig, callback);
    }

    public static boolean isEmpty(String str) {
        return TextUtils.isEmpty(str) || str == null;
    }

    public static boolean isEmptyTask(String str) {
        return TextUtils.isEmpty(str) || str == null || str.equals("0");
    }


    /**
     * 进入淘宝页面
     *
     * @param context
     * @param tbPath
     */
    public static void goTaobao(Context context, String tbPath) {
        if (TextUtils.isEmpty(tbPath)) {
            Toast.makeText(Application.instance, "淘宝地址有误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkApkExist(Application.instance, "com.taobao.taobao")) {
            Intent intent = new Intent();
            intent.setAction("Android.intent.action.VIEW");
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(tbPath);
//            Uri uri = Uri.parse(tbPath); // 商品地址
//            intent.setData(uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
            context.startActivity(intent);
        } else {
            Toast.makeText(Application.instance, "本机未安装淘宝应用", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 进入jd页面
     *
     * @param context
     * @param thridPlatSearchKey
     */
    public static void goJd(Context context, String id, String thridPlatSearchKey) {

        if (checkApkExist(Application.instance, "com.jingdong.app.mall")) {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            Uri uri = Uri.parse("openapp.jdmobile://virtual?params=%7B%22sourceValue%22:%220_productDetail_97%22,%22des%22:%22productDetail%22,%22skuId%22:%22"+id+"%22,%22category%22:%22jump%22,%22sourceType%22:%22PCUBE_CHANNEL%22%7D ");
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setData(uri);
//            context.startActivity(intent);
            if (thridPlatSearchKey != null && !TextUtils.isEmpty(thridPlatSearchKey)) {
                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(thridPlatSearchKey);
                ToastUtil.getInstance().showToast(context, "链接已复制！");
            }
            Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage("com.jingdong.app.mall");
            LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(LaunchIntent);
        } else {
            Toast.makeText(Application.instance, "本机未安装京东应用", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 进入tb页面
     *
     * @param context
     * @param thridPlatSearchKey
     */
    public static void gotb(Context context, String id, String thridPlatSearchKey) {
        if (checkApkExist(Application.instance, "com.taobao.taobao")) {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            Uri uri = Uri.parse("taobao://item.taobao.com/item.htm?id="+id);
////        Uri uri = Uri.parse("tmall://tmallclient/?{\"action\":\\”item:id=36615660686\\”}");
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setData(uri);
//            context.startActivity(intent);
            if (thridPlatSearchKey != null && !TextUtils.isEmpty(thridPlatSearchKey)) {
                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(thridPlatSearchKey);
                ToastUtil.getInstance().showToast(context, "淘宝口令已复制！");
            }
            Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage("com.taobao.taobao");
            LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(LaunchIntent);
        } else {
            Toast.makeText(Application.instance, "本机未安装淘宝应用", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 进入tb页面
     *
     * @param context
     * @param thridPlatSearchKey
     */
    public static void gotm(Context context, String id, String thridPlatSearchKey) {
        if (checkApkExist(Application.instance, "com.tmall.wireless")) {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            Uri uri = Uri.parse("tmall://tmallclient/?{\"action\":\\”item:id="+id+"\\”}");
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setData(uri);
//            context.startActivity(intent);
            if (thridPlatSearchKey != null && !TextUtils.isEmpty(thridPlatSearchKey)) {
                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(thridPlatSearchKey);
                ToastUtil.getInstance().showToast(context, "链接口令已复制！");
            }
            Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage("com.tmall.wireless");
            LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(LaunchIntent);
        } else {
            Toast.makeText(Application.instance, "本机未安装天猫应用", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 复制指定文本到剪切板
     *
     * @param mContext
     * @param s
     */
    public static void copy(Context mContext, String s) {
        ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(s);
        ToastUtil.getInstance().showToast(mContext, "复制成功！");
    }

    public static void goShowPic(Context mContext, ArrayList<PhotoInfo> list, int position) {
        Intent intent = new Intent(mContext, PhotoPreviewActivity.class);
        intent.putExtra(PhotoPreviewActivity.PHOTO_LIST, list);
        intent.putExtra(PhotoPreviewActivity.PHOTO_INDEX, position);
        mContext.startActivity(intent);
    }
}